import {ipcMain, app, screen} from 'electron'

const Store = require('electron-store')
const store = new Store()

//注册窗口
ipcMain.on('tag-add', (event, id) => {
  let tagSenders = getSender()
  tagSenders[id] = event.sender
  app.tagSenders = tagSenders
  console.log('添加一个窗口， 剩余窗口数：' + Object.keys(tagSenders).length)
})
//删除窗口
ipcMain.on('tag-del', (event, id) => {
  let tagSenders = getSender()
  delete tagSenders[id]
  app.tagSenders = tagSenders
  console.log('删除一个窗口， 剩余窗口数：' + Object.keys(tagSenders).length)
})
//登录
ipcMain.on('login', (event, info) => {
  app.userInfo = info
  app.mainSender = event.sender
  //向窗口推送登录信息
  sendDataToTags('login', info);
  console.log('客户登录：向所有窗口发送用户信息' )
})
//登出
ipcMain.on('logout', (event, info) => {
  app.userInfo = null
  //向窗口推送登出事件
  sendDataToTags('logout');
  console.log('客户退出：向所有窗口发送登出事件' )
})
//推送配置信息
ipcMain.on('settingChange', (event, info) => {
  //向窗口推送登出事件
})

ipcMain.on('getUserInfo', (event) => {
  event.sender.send('responseGetUserInfo', app.userInfo)
})
//注册标签数据
ipcMain.on('getTagData', (event) => {
  event.sender.send('responseGetTagData', app.tagData)
})
ipcMain.on('tagData', (event, data) => {
  app.tagData = data
})
ipcMain.on('tagDataChange', (event, data) => {
  app.tagData = data
  sendDataToTags('tagDataChange', data);
})


function sendDataToTags (event, data) {
  //向窗口推送登出事件
  let tagSenders = getSender()
  let ids = Object.keys(tagSenders)
  ids.forEach(function(id){
    let sender = tagSenders[id]
    sender.send(event, data);
  })
}

function getSender(){
  let tagSenders = app.tagSenders
  tagSenders = tagSenders ? tagSenders : {}
  return tagSenders
}

ipcMain.on('setSettings', function (event, settings) {
  store.set('settings', settings)
  // 关闭 开机自启动
  let openAtLogin = false
  if (settings.autoStart == 1) {
    openAtLogin = true
  }
  app.setLoginItemSettings({
    openAtLogin: openAtLogin
  })
})


ipcMain.on('downPath', function (event, downPath) {
  app.downPath = downPath
})
